package top.superflow.flow.inner

import org.springframework.context.ApplicationContext
import top.superflow.exception.RequestUnsupportedException
import top.superflow.flow.config.dependency.DependencyManager
import top.superflow.flow.runtime.resource.RuntimeResource

trait SpringApplicationContextAware {

  private val EXPECTED_APPLICATION_CONTEXT_KEY = "applicationContext"

  protected def getApplicationContext(dependencies : Map[String, Any]): ApplicationContext ={
    DependencyManager.getInstance.getDependency(EXPECTED_APPLICATION_CONTEXT_KEY, classOf[ApplicationContext], dependencies).asInstanceOf[ApplicationContext]
  }

  protected def getApplicationContextResource(dependencies : Map[String, RuntimeResource]): ApplicationContext ={
    DependencyManager.getInstance.validateManifest(EXPECTED_APPLICATION_CONTEXT_KEY, dependencies)
    val applicationContextResource = dependencies.get(EXPECTED_APPLICATION_CONTEXT_KEY)
    val applicationContext =  applicationContextResource.get
    if(applicationContext == null){
      throw new RequestUnsupportedException("The application context should not be null")
    }

    applicationContext.get[ApplicationContext](classOf[ApplicationContext])
  }
}
